/**
 * 文本差异比较工具
 */
import * as Diff from 'diff';
import { TextDiff, DiffStatistics } from '../../types/ai.ts';

/**
 * 计算两个文本间的差异
 * @param originalText 原始文本
 * @param modifiedText 修改后文本
 * @returns 差异比较结果，包括HTML格式的差异表示和统计信息
 */
export const calculateTextDiff = (originalText: string, modifiedText: string): TextDiff => {
  // 安全检查，确保输入有效
  if (!originalText && !modifiedText) {
    return createEmptyDiff();
  }
  
  // 确保文本变量为字符串
  const original = originalText?.toString() || '';
  const modified = modifiedText?.toString() || '';
  
  try {
    // 计算文本差异
    const diffResult = Diff.diffChars(original, modified);
    
    // 转换为HTML表示
    let diffHtml = '';
    let addedChars = 0;
    let removedChars = 0;
    let unchangedChars = 0;
    
    for (const part of diffResult) {
      // 对HTML特殊字符进行转义，防止XSS和布局破坏
      const escapedValue = escapeHtml(part.value);
      
      if (part.added) {
        // 添加的内容用ins标签包裹
        diffHtml += `<ins class="ai-replaced-text-added">${escapedValue}</ins>`;
        addedChars += part.value.length;
      } else if (part.removed) {
        // 删除的内容用del标签包裹
        diffHtml += `<del class="ai-replaced-text-deleted">${escapedValue}</del>`;
        removedChars += part.value.length;
      } else {
        // 未更改的内容直接显示
        diffHtml += escapedValue;
        unchangedChars += part.value.length;
      }
    }
    
    // 计算统计信息
    const totalOriginal = original.length;
    const totalModified = modified.length;
    const modificationRate = totalOriginal > 0 
      ? Math.round((removedChars / totalOriginal) * 100 * 10) / 10 
      : 0;
    const growthRate = totalOriginal > 0 
      ? Math.round(((totalModified - totalOriginal) / totalOriginal) * 100 * 10) / 10 
      : totalModified > 0 ? 100 : 0;
    
    // 创建并返回完整的差异结果
    return {
      original,
      modified,
      diffHtml,
      statistics: {
        addedChars,
        removedChars,
        unchangedChars,
        totalOriginal,
        totalModified,
        modificationRate,
        growthRate
      }
    };
  } catch (error) {
    console.error('生成文本差异时出错:', error);
    
    // 返回基本的比较结果，确保UI不会崩溃
    return {
      original,
      modified,
      diffHtml: `<div>${escapeHtml(modified)}</div>`,
      statistics: {
        addedChars: 0,
        removedChars: 0,
        unchangedChars: original.length,
        totalOriginal: original.length,
        totalModified: modified.length,
        modificationRate: 0,
        growthRate: modified.length > original.length ? 100 : 0
      }
    };
  }
};

/**
 * 创建空差异结果
 * 用于处理无效输入的情况
 */
function createEmptyDiff(): TextDiff {
  return {
    original: '',
    modified: '',
    diffHtml: '',
    statistics: {
      addedChars: 0,
      removedChars: 0,
      unchangedChars: 0,
      totalOriginal: 0,
      totalModified: 0,
      modificationRate: 0,
      growthRate: 0
    }
  };
}

/**
 * 转义HTML特殊字符
 * @param text 要转义的文本
 * @returns 转义后的安全文本
 */
function escapeHtml(text: string): string {
  if (!text) return '';
  
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;')
    // 保留换行符
    .replace(/\n/g, '<br/>');
}

/**
 * 将差异结果转换为编辑器可用的HTML
 * @param diffResult 差异比对结果
 * @returns 编辑器可使用的HTML字符串
 */
export const diffToEditorHtml = (diffResult: TextDiff): string => {
  return diffResult.diffHtml;
}; 